package com.yc.testupload.controller;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.yc.testupload.util.DatabaseUtil;

/**
 * 素材保存Servlet
 * 处理将Word文件上传至七牛云后生成的文件地址保存到素材表的请求
 */
@WebServlet(name = "materialSaveServlet", value = "/api/saveToMaterial")
public class MaterialSaveServlet extends HttpServlet {
    
    // 日志记录器
    private static final Logger logger = LogManager.getLogger(MaterialSaveServlet.class);
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型
        response.setContentType("application/json;charset=UTF-8");
        logger.info("[请求入口] 收到保存素材请求");
        
        // 读取请求体中的JSON数据
        StringBuilder sb = new StringBuilder();
        String line;
        try (BufferedReader reader = request.getReader()) {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }
        
        String jsonBody = sb.toString();
        logger.info("[请求数据] 接收的JSON数据: {}", jsonBody);
        
        // 解析JSON数据（简化处理，实际应用中应使用JSON解析库）
        String title = extractValueFromJson(jsonBody, "title");
        String content = extractValueFromJson(jsonBody, "content");
        String sourceUrl = extractValueFromJson(jsonBody, "sourceUrl");
        String categoryIdStr = extractValueFromJson(jsonBody, "categoryId");
        
        // 验证必要参数
        if (title == null || content == null || sourceUrl == null || categoryIdStr == null) {
            String errorMsg = "缺少必要参数: title, content(七牛云文件地址), sourceUrl, categoryId 都是必填项";
            logger.error(errorMsg);
            sendJsonResponse(response, false, errorMsg, -1);
            return;
        }
        
        // 验证content字段是否为有效的URL格式（七牛云文件地址）
        if (!content.startsWith("http://") && !content.startsWith("https://")) {
            String errorMsg = "content参数格式错误: 应为七牛云文件地址（以http://或https://开头）";
            logger.error(errorMsg);
            sendJsonResponse(response, false, errorMsg, -1);
            return;
        }
        
        int categoryId;
        try {
            categoryId = Integer.parseInt(categoryIdStr);
        } catch (NumberFormatException e) {
            logger.error("分类ID格式错误: {}", categoryIdStr);
            sendJsonResponse(response, false, "分类ID格式错误", -1);
            return;
        }
        
        // 获取当前时间戳（秒）
        long currentTime = System.currentTimeMillis() / 1000;
        
        // 保存到素材表
        int materialId = saveToMaterialTable(request, title, content, categoryId, sourceUrl, currentTime);
        
        // 返回结果
        if (materialId > 0) {
            logger.info("素材保存成功，ID: {}", materialId);
            sendJsonResponse(response, true, "素材保存成功", materialId);
        } else {
            logger.error("素材保存失败");
            sendJsonResponse(response, false, "素材保存失败", -1);
        }
    }
    
    /**
     * 将Word文件URL保存到素材表
     * content参数实际存储的是Word文件上传至七牛云后生成的文件地址
     */
    private int saveToMaterialTable(HttpServletRequest request, String title, String content, int categoryId, String sourceUrl, long currentTime) {
        logger.info("开始将内容保存到素材表: {}", title);
        long startTime = System.currentTimeMillis();
        int materialId = -1;
        Connection conn = null;
        PreparedStatement pstmt = null;
        
        try {
            // 从session中获取用户ID（注意键名是userId，首字母大写）
            Integer userId = (Integer) request.getSession().getAttribute("userId");
            if (userId == null) {
                logger.error("未从session中获取到用户ID（session键名：userId）");
                return -1; // 返回错误
            }
            logger.info("从session中获取的用户ID: {}", userId);
            
            // 获取数据库连接
            conn = DatabaseUtil.getConnection();
            logger.info("已获取数据库连接");
            
            // 保存到wk_material表
            String sql = "INSERT INTO wk_material (title, content, category_id, user_id, source_url, add_time, edit_time, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            pstmt = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
            pstmt.setString(1, title);
            pstmt.setString(2, content);
            pstmt.setInt(3, categoryId);
            pstmt.setInt(4, userId); // 从session中获取的用户ID
            pstmt.setString(5, sourceUrl);
            pstmt.setLong(6, currentTime);
            pstmt.setLong(7, currentTime);
            pstmt.setInt(8, 1); // status，设为1（可用）
            
            int rowsAffected = pstmt.executeUpdate();
            logger.info("执行SQL语句影响的行数: {}", rowsAffected);
            
            // 获取生成的素材ID
            if (rowsAffected > 0) {
                try (java.sql.ResultSet rs = pstmt.getGeneratedKeys()) {
                    if (rs.next()) {
                        materialId = rs.getInt(1);
                        logger.info("成功保存到素材表，素材ID: {}", materialId);
                    }
                }
            }
            
        } catch (SQLException e) {
            logger.error("保存到素材表失败: {}", e.getMessage(), e);
        } finally {
            // 关闭数据库资源
            if (pstmt != null) {
                try { pstmt.close(); } catch (SQLException e) { logger.error("关闭PreparedStatement失败", e); }
            }
            DatabaseUtil.closeConnection(conn);
        }
        
        long endTime = System.currentTimeMillis();
        logger.info("素材表操作完成，耗时: {} ms", (endTime - startTime));
        return materialId;
    }
    
    /**
     * 从JSON字符串中提取指定键的值（简化实现）
     */
    private String extractValueFromJson(String json, String key) {
        try {
            String searchKey = "\"" + key + "\":";
            int startIndex = json.indexOf(searchKey);
            if (startIndex == -1) {
                return null;
            }
            
            startIndex += searchKey.length();
            // 跳过空格
            while (startIndex < json.length() && json.charAt(startIndex) == ' ') {
                startIndex++;
            }
            
            // 处理字符串类型的值
            if (json.charAt(startIndex) == '\"') {
                startIndex++;
                int endIndex = json.indexOf('\"', startIndex);
                while (endIndex != -1 && json.charAt(endIndex - 1) == '\\') {
                    endIndex = json.indexOf('\"', endIndex + 1);
                }
                if (endIndex != -1) {
                    return json.substring(startIndex, endIndex).replace("\\\"", "\"");
                }
            }
            // 处理数字类型的值
            else if (Character.isDigit(json.charAt(startIndex)) || json.charAt(startIndex) == '-') {
                int endIndex = startIndex;
                while (endIndex < json.length() && (Character.isDigit(json.charAt(endIndex)) || json.charAt(endIndex) == '.' || json.charAt(endIndex) == '-')) {
                    endIndex++;
                }
                return json.substring(startIndex, endIndex);
            }
        } catch (Exception e) {
            logger.error("解析JSON数据错误: {}", e.getMessage());
        }
        return null;
    }
    
    /**
     * 发送JSON格式的响应
     */
    private void sendJsonResponse(HttpServletResponse response, boolean success, String message, int id) throws IOException {
        PrintWriter out = response.getWriter();
        try {
            out.println("{\n" +
                        "  \"success\": " + success + ",\n" +
                        "  \"message\": \"" + message + "\",\n" +
                        "  \"id\": " + id + "\n" +
                        "}");
        } finally {
            out.close();
        }
    }
    
    @Override
    public void destroy() {
        logger.info("素材保存Servlet已销毁");
        super.destroy();
    }
}